﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using HtmlAgilityPack;

namespace VH.SharePoint.Api.Helpers
{
    public static class WlwHelper
    {
        public static bool IsRequestedByWlw()
        {
            return IsRequestedByWlw(HttpContext.Current);
        }

        public static bool IsRequestedByWlw(HttpContext context)
        {
            if (context == null) return false;
            return context.Request.UserAgent.StartsWith("Windows Live Writer");
        }

        public static string WrapUploadContent(string html, string toRealRootFolder)
        {
            if (string.IsNullOrEmpty(html)) return string.Empty;
            var htmlDoc = new HtmlDocument();
            htmlDoc.LoadHtml(html);
            var regex = new Regex("_attach", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);
            var hrefNodes = from d in htmlDoc.DocumentNode.Descendants()
                            where
                                d.Name.Equals("a", StringComparison.InvariantCultureIgnoreCase) &&
                                d.Attributes.Contains("href") &&
                                regex.IsMatch(d.Attributes["href"].Value)
                            select d;
            var imgNodes = from d in htmlDoc.DocumentNode.Descendants()
                           where
                               d.Name.Equals("img", StringComparison.InvariantCultureIgnoreCase) &&
                               d.Attributes.Contains("src") &&
                               regex.IsMatch(d.Attributes["src"].Value)
                           select d;

            foreach (var hrefNode in hrefNodes)
            {
                var attr = hrefNode.Attributes["href"];
                attr.Value = regex.Replace(attr.Value, toRealRootFolder);
            }
            foreach (var imgNode in imgNodes)
            {
                var attr = imgNode.Attributes["src"];
                attr.Value = regex.Replace(attr.Value, toRealRootFolder);
            }

            return htmlDoc.DocumentNode.InnerHtml;
        }
    }
}
